<template>
  <div class="dept">
    <el-button type="primary" style="margin-left: 10px" @click="create_dept = true">新增</el-button>
    <el-form
        :inline="true"
        :model="formInline"
        class="demo-form-inline"
        style="margin-top: 0px; line-height: 10px"
    >

      <el-table
          :data="tableData"
          style="width: 100%;margin: 10px"
          border
          stripe
          row-key="sequence_num"
          default-expand-all
          :default-sort="{prop: 'name', order: 'ascending '}"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
        >
        <el-table-column
            prop="name"
            label="名称"
            sortable
            width="180">
        </el-table-column>
        <el-table-column
            prop="sequence_num"
            label="排序号"
            sortable
            width="300">
        </el-table-column>
        <el-table-column
            prop="status"
            label="状态"
            width="300"
            :filters="[{ text: '正常', value: '正常' }, { text: '异常', value: '异常' }]"
            :filter-method="filterTag"
            filter-placement="bottom-end">
          <template slot-scope="scope">
            <el-tag
                :type="scope.row.tag === '正常' ? 'success' : 'danger'"
                disable-transitions>{{ scope.row.tag }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
            prop="create_time"
            label="创建时间"
            width="180">
        </el-table-column>
        <el-table-column
            prop="operate"
            label="操作"
            :formatter="formatter">
          <template>
            <el-button type="text" size="small" @click="dialogFormVisible = true">编辑</el-button>
            <span style="color: #E4E7ED;margin-left: 10px;margin-right: 10px">|</span>
            <el-button type="text" size="small">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

    </el-form>

    <el-dialog title="编辑部门" :visible.sync="dialogFormVisible">
      <el-form :model="form">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="请选择部门状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="异常" value="异常"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="新增部门" :visible.sync="create_dept">
      <el-form :model="form">
        <el-form-item label="名称" :label-width="formLabelWidth">
          <el-input v-model="form.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="状态" :label-width="formLabelWidth">
          <el-select v-model="form.status" placeholder="请选择部门状态">
            <el-option label="正常" value="正常"></el-option>
            <el-option label="异常" value="异常"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="create_dept = false">取 消</el-button>
        <el-button type="primary" @click="create_dept = false">确 定</el-button>
      </div>
    </el-dialog>
    <div class="course_pagination block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page.sync="filter.page"
          :page-sizes="[2, 3, 5, 10]"
          :page-size="filter.size"
          layout="sizes, prev, pager, next"
          :total="course_total">
      </el-pagination>
    </div>

  </div>
</template>

<script>
import store from "@/store";

export default {
  name: 'Dept',
  data() {
    return {
      tableData: [{
        create_time: '2016-05-02',
        name: '上海分部',
        sequence_num: '1',
        tag: '正常',
        children: [{
          create_time: '2016-05-02',
          name: '上海-开发',
          sequence_num: '2',
          tag: '正常',
        }, {
          create_time: '2016-05-02',
          name: '上海-运维',
          sequence_num: '3',
          tag: '正常',
        }]
      }, {
        create_time: '2016-05-04',
        name: '山东分部',
        sequence_num: '4',
        tag: '异常'
      }, {
        create_time: '2016-05-01',
        name: '浙江分部',
        sequence_num: '5',
        tag: '正常',
        children: [{
          create_time: '2016-05-02',
          name: '浙江-开发',
          sequence_num: '6',
          tag: '正常',
        }, {
          create_time: '2016-05-02',
          name: '浙江-运维',
          sequence_num: '7',
          tag: '正常',
        }]
      }],
      activeTab: '',
      course_total: 0,   // 当前总数量
      filter: {
        course_category: 0, // 当前用户选择的课程分类，刚进入页面默认为全部，值为0
        ordering: "orders",    // 数据的排序方式，默认值是orders，表示对于id进行降序排列
        size: 5,       // 单页数据量
        page: 1,
      },
      formInline: {
        name: "",
        depart_type_name: "",
        deptType: "",
      },
      user: {},
      deptTable: [],
      multipleSelection: [],
      pageTotal: "",
      departmentPageDto: {},
      departmentClassification: [],
      departmentType: [],
      drawer: false,
      direction: "rtl",
      dialogFormVisible: false,
      create_dept: false,
      form: {
        name: '',
        region: '',
        date1: '',
        date2: '',
        delivery: false,
        type: [],
        resource: '',
        desc: ''
      },
      formLabelWidth: '120px'
    };
  },
  created() {
    this.$axios
        .get(this.$settings.BASE_URL + 'user/depart/')
        .then((Response) => {
          this.deptTable = Response.data.results;
          this.departmentPageDto = Response.data.count
        })
        .catch((error) => {
          console.error(error);
        });
    this.user_type = this.$getSessionStorage("user_type");
    //axios查询科室列表条数请求
    this.paging(1);
    //axios查询科室分类请求
    this.selectDepartmentClassification();
    this.selectDepartmentType();
    this.get_course();
  },
  watch: {
    // 监听属性
    // 监听筛选过滤和过滤，如果发生改变就重新加载页面数据
    "filter.course_category": function () {
      this.filter.page = 1;
      this.get_course();
    },
    "filter.ordering": function () {
      this.get_course();
    },
    "filter.size": function () {
      this.get_course();
    },
    "filter.page": function () {
      this.get_course();
    },
  },
  methods: {

    tableRowClassName({row, rowIndex}) {
      if (rowIndex === 1) {
        return 'warning-row';
      } else if (rowIndex === 3) {
        return 'success-row';
      }
      return '';
    },
    handleSizeChange(val) {
      // 每页数据量发生变化时执行的方法
      this.filter.page = 1;
      this.filter.size = val;
    },
    handleCurrentChange(val) {
      // 页码发生变化时执行的方法
      this.filter.page = val;
    },
    updateDepartment(row) {
      if (this.user_type === "管理员") {
        console.log(row.id);
        this.form = row;
      } else {
        alert("很抱歉,您没有权限编辑科室");
        location.reload();
      }
    },
    submitDepartment() {
      // this.user = this.$getSessionStorage("user");
      //axios编辑科室请求
      let id = this.form.id
      this.$axios
          .put(this.$settings.BASE_URL + `user/depart/${id}/`, {
            add_name: this.form.add_name,
            department_code: this.form.department_code,
            name: this.form.name,
            depart_type: this.form.deptType,
          })
          .then((Response) => {
            this.$message({
              message: '编辑成功',
              type: 'success',
              duration: 1000
            })
            window.setTimeout(function () {
              location.reload();
            }, 2000)
          })
          .catch((error) => {
            console.error(error);
            alert("编辑科室失败");
          });
    },
    handleClose(done) {
      this.$confirm("确认关闭？")
          .then((_) => {
            done();
          })
          .catch((_) => {
          });
    },
    deteleDepartment(row) {
      if (this.user_type === "管理员") {
        this.$confirm("确认删除此科室？")
            .then((_) => {
              console.log(row.id);
              //axios通过id删除科室
              this.$axios.delete(this.$settings.BASE_URL + `user/depart/${row.id}/`).then((Response) => {
                this.$message({
                  message: `删除药物${this.form.name}成功`,
                  type: 'success',
                  duration: 1000
                })
                window.setTimeout(function () {
                  location.reload();
                }, 1000)
              }).catch((error) => {
                console.error(error);
                alert("删除科室失败");
              });
            })
            .catch((_) => {
            });
      } else {
        this.$message({
          message: "很抱歉,您没有权限删除科室",
          type: 'success',
          duration: 1000
        })
      }
    },
    resetForm(formName) {
      location.reload();
    },
    newDepartment() {
      if (this.user_type === "管理员") {
        this.$router.push({
          path: "/index/newDepartment",
        });
      } else {
        alert("很抱歉,您没有权限新建科室");
      }
    },
    batchDelete() {
      if (this.user_type === "管理员") {
        if (this.multipleSelection.length === 0) {
          alert("至少选择一条数据进行批量删除");
        } else {
          this.$confirm("确认批量删除科室？")
              .then((_) => {
                //axios批量删除请求
                this.$axios
                    .post(
                        "/department/removeDepartmentBatch",
                        this.multipleSelection
                    )
                    .then((Response) => {
                      alert("批量删除成功");
                    })
                    .catch((error) => {
                      console.error(error);
                    });
              })
              .catch((_) => {
              });
        }
      } else {
        alert("很抱歉,您没有权限批量删除科室");
      }
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
      console.log(val);
    },
    get_course() {
      // 排序
      let filters = {
        ordering: this.filter.ordering, // 排序
      };
      // 判决是否进行分类课程的展示
      if (this.filter.course_category > 0) {
        filters.course_category = this.filter.course_category;
      }
      // 设置单页数据量
      if (this.filter.size > 0) {
        filters.size = this.filter.size;
      } else {
        filters.size = 5;
      }

      // 设置当前页码
      if (this.filter.page > 1) {
        filters.page = this.filter.page;
      } else {
        filters.page = 1;
      }
      // 获取课程列表信息
      this.$axios.get(this.$settings.BASE_URL + 'user/depart/', {
        params: filters
      }).then(response => {
        console.log(response.data)
        this.deptTable = response.data.results;
        this.course_total = response.data.count;
      }).catch(() => {
        this.$message({
          message: "获取课程信息有误，请联系客服工作人员"
        })
      })
    },
    select() {
      let depart_type = this.form.deptType
      let name = this.formInline.name
      if (name.length === 0 || depart_type.length === 0) {
        this.$message({
          message: '请在框中输入或选择内容',
          type: 'warning',
          duration: 1000
        })
      } else {
        this.$axios.get(this.$settings.BASE_URL + `user/departsearch/?name=${name}` + '&' + `depart_type=${depart_type}`).then(response => {
          this.deptTable = response.data
        }).catch(() => {
          this.$message({
            message: '出现异常',
            type: 'warning',
            duration: 1000
          })
        })
      }

    },
  },
  computed: {
    tabList() {
      return store.getters['getTabs']
    },
  },
}
</script>

<style scoped>
.text {
  font-size: 14px;
}

.item {
  padding: 18px 0;
}

.box-card-departemt {
  width: 1600px;
}

.el-main {
  line-height: 0px;
}

.el-table .warning-row {
  background: oldlace;
}

.el-table .success-row {
  background: #f0f9eb;
}


</style>